<?php
/**
 * basicPingFMClass
 * 
 * A Class Library that handles pings to PingFM
 *
 * @version 1.0
 * @author      Daniel Eliasson Stilero AB - http://www.stilero.com
 * @copyright	Copyright (c) 2011 Stilero AB. All rights reserved.
 * @license	GPLv2
* 	Joomla! is free software. This version may have been modified pursuant
* 	to the GNU General Public License, and as distributed it includes or
* 	is derivative of works licensed under the GNU General Public License or
* 	other free or open source software licenses.
 *
 *  This file is part of AutoSocialShare. 
 * 
 *     AutoSocialShare is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AutoSocialShare is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AutoSocialShare.  If not, see <http://www.gnu.org/licenses/>.
 */
class basicPingFMClass {
    const HTTP_STATUS_FOUND = 303; //All ok but prefers other options
    const HTTP_STATUS_OK = 200; //Returned on all ok
    const HTTP_STATUS_FORBIDDEN = 403; //Returned from Twitter on duplicate tweets
    var $article;
    var $message;
    var $inBackend;
    var $errorMessage;
    var $errorOccured;
    
    function __construct($config) {
        $this->errorOccured = FALSE;
        $this->errorMessage = "";
        $this->config = array_merge(
            array(
            'loginFormURL'          =>      'http://ping.fm/m/login/',
            'loginPostURL'          =>      'http://ping.fm/m/login/',
            'messagePostURL'        =>      'http://ping.fm/m/',
            'username'              =>      '',
            'password'              =>      '',
            'serviceToUse'          =>      '',
            'curlWebAgent'          =>      'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)',
            'curlPost'              =>      1,
            'curlSSLVerifyPeer'     =>      false,
            'curlSSLVerifyHost'     =>      2,
            'curlCookieFile'        =>      '',
            'curlReturnTransfer'    =>      1,
            'curlFollowLocation'    =>      0,
            ),
        $config);
    }
    
    public function sendPingMessage($message) {
        $this->message = $message;
        $this->createCookieFile();
        $this->getLoginFormPage();
        $this->doLogin();
        $this->doSendMessage();
        if( ! $this->errorOccured ){
            return 200;
        }else{
            return $this->errorMessage;
        }
    }

    private function createCookieFile() {
        $cookieFileCreated = tempnam(DS."tmp", "cookies");
        if (!$cookieFileCreated){
            $this->errorMessage = 'Could not create file to store sessions, check your directory permissions.';
            $this->errorOccured = TRUE;
            return FALSE;
        }
        $this->config['curlCookieFile'] = $cookieFileCreated;
    }

    private function getLoginFormPage() {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,               $this->config['loginFormURL']); 		
        curl_setopt($ch, CURLOPT_USERAGENT,         $this->config['curlWebAgent']); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,    $this->config['curlReturnTransfer']); 
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,    $this->config['curlFollowLocation']);
        curl_setopt($ch, CURLOPT_COOKIEFILE,        $this->config['curlCookieFile']);
        curl_setopt($ch, CURLOPT_COOKIEJAR,         $this->config['curlCookieFile']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,    $this->config['curlSSLVerifyHost']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,    $this->config['curlSSLVerifyPeer']);
        $twLoginPage = curl_exec ($ch);	
        $twLoginPageResultsArray = curl_getinfo($ch);
        if( $twLoginPageResultsArray['http_code'] != self::HTTP_STATUS_OK ){
            $this->errorMessage = "Failed to contact Twitter (code:".$twLoginPageResultsArray['http_code'].")";
            $this->errorOccured = TRUE;
            curl_close ($ch);
            return FALSE;
        }
        curl_close ($ch);
        return $twLoginPage;
    }

    private function doLogin() {
        if( $this->errorOccured ){
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,               $this->config['loginPostURL']);
        curl_setopt($ch, CURLOPT_USERAGENT,         $this->config['curlWebAgent']);
        curl_setopt($ch, CURLOPT_POST,              $this->config['curlPost']);
        curl_setopt($ch, CURLOPT_POSTFIELDS,        $this->getLoginPostfieldsHTTPQuery()); //Build a query from the postarray
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,    $this->config['curlReturnTransfer']);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,    $this->config['curlFollowLocation']);
        curl_setopt($ch, CURLOPT_REFERER,           $this->config['loginFormURL']);		//set a spoof referrer
        curl_setopt($ch, CURLOPT_COOKIEFILE,        $this->config['curlCookieFile']);
        curl_setopt($ch, CURLOPT_COOKIEJAR,         $this->config['curlCookieFile']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,    $this->config['curlSSLVerifyHost']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,    $this->config['curlSSLVerifyPeer']);
        $twitterLoginResults = curl_exec ($ch);
        $twitterLoginResultsArray = curl_getinfo($ch);
        if( $twitterLoginResultsArray['http_code'] != self::HTTP_STATUS_FOUND ){
            $this->errorMessage = "Failed to login to Ping.FM (code:".$twitterLoginResultsArray['http_code'].")";
            $this->errorOccured = TRUE;
            curl_close ($ch);
            return FALSE;
        }
        curl_close ($ch);
        return TRUE;
    }

    private function doSendMessage() {
        if($this->errorOccured){
            return;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,               $this->config['messagePostURL']);
        curl_setopt($ch, CURLOPT_USERAGENT,         $this->config['curlWebAgent']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,    $this->config['curlReturnTransfer']);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,    $this->config['curlFollowLocation']);
        curl_setopt($ch, CURLOPT_REFERER,           $this->config['loginFormURL']);
        curl_setopt($ch, CURLOPT_COOKIEFILE,        $this->config['curlCookieFile']);
        curl_setopt($ch, CURLOPT_COOKIEJAR,         $this->config['curlCookieFile']);
        curl_setopt($ch, CURLOPT_POST,              $this->config['curlPost']);
        curl_setopt($ch, CURLOPT_POSTFIELDS,        $this->getPostHTTPQuery());
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,    $this->config['curlSSLVerifyHost']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,    $this->config['curlSSLVerifyPeer']);
        $result = curl_exec ($ch);
        $tweetPostResultsArray = curl_getinfo($ch);
        curl_close ($ch);
        //Kill the cookie, we don't need it anymore
        unlink($this->config['curlCookieFile']);
        switch ($tweetPostResultsArray['http_code']) {
            case self::HTTP_STATUS_OK:
                return true;
                break;
            case self::HTTP_STATUS_FOUND:
                return true;
                break;
            default:
                $this->errorMessage = "Ping Failed (code:".$tweetPostResultsArray['http_code'].")";
                $this->errorOccured = TRUE;
                break;
        }
        return false;
    } 

    public function setLoginDetails($username, $password) {
        $this->config['username'] = $username;
        $this->config['password'] = $password;
    }

    private function getLoginPostfieldsHTTPQuery() {
        $loginPostFieldsArray = array(
            'email'	=>  $this->config['username'],
            'password'  =>  $this->config['password']
        );
        $loginHTTPQuery = http_build_query($loginPostFieldsArray);
        return $loginHTTPQuery;           
    }
    
    private function getPostHTTPQuery() {
        $postFieldsArray = array(
            'message'           =>  $this->message,
            'service'           =>  $this->config['serviceToUse']
        );
        $postHTTPQuery = http_build_query($postFieldsArray);
        return $postHTTPQuery;           
    }
}

?>
